<?php
namespace jy_merch;
defined('BY_JYA') or exit('error');
/*
	本插件：$this->model('member')->方法名();
	其他地方调用：model('jy_merch/member')->方法名();
*/
class member extends \plugin{
	/*
		绑定粉丝;
		同一客户，可以跟不同类型的商户绑定推广关系；同一类型不能重复；
	*/
	public function up_catefans($merchid=0,$uid=0,$type=0){
			$uid=$uid?:$_SESSION['uid'];
			$check=$this->check_catefans($merchid,$uid,$type);
			if(!$check){
				return false;
			}
			$data=array(
				'uniacid'=>$_SESSION['uniacid'],
				'merchid'=>$merchid,
				'mid'=>$uid,
				'type'=>$type,
				'createtime'=>time(),
			);
			pdo_insert('jy_merch_catefans',$data);
			return true;
	}
	public function check_catefans($merchid=0,$uid=0,$type=0){
			$uid=$uid?:$_SESSION['uid'];
			$check=pdo_get('jy_merch_catefans',array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			if($check['id']){
				return false;
			}
			if(!$type){
				$type=$this->get_merch_type($merchid);	
			}
			$catecheck=pdo_get('jy_merch_catefans',array('type'=>$type,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));	
			if($catecheck['id']){
				return false;
			}
			return true;
	}
	//api访问页面时，重新进入页面
	public function apiget_openid($merchid=0,$url=''){
		$_SESSION['onemerchid']=$merchid;
		$url=custom_url($url,true);
		if(!$_SESSION['onemerchid'] || $_SESSION['isopenid'.$merchid] || !$merchid || $_SESSION['isopenid'.$merchid] || !$this->setting['isone_wechat']){
			return false;
		}
		$onewechat = pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'onewechat');
		$onewechat=json_decode($onewechat,true);
		if(!$onewechat || !$onewechat['isopen'] || !$onewechat['appid'] || !$onewechat['appsecret']){
			return false;
		}
		if($_SESSION['container']!='wechat'){
			return 'need';
		}
		exi('','',$url);
		return true;
	}
	//获取商户OPENDid
	public function get_openid($merchid=0){
		if(!$merchid || $_SESSION['isopenid'.$merchid]){
			return false;
		}
		if(!$_SESSION['openid'.$merchid] && !$_SESSION['isopenid'.$merchid]){
			$url=$this->wechat_auth_base_url($merchid);
			if($url){
				header('location:'.$url);exit;
			}
		}
	}
	public function get_wxappopenid($merchid=0,$code=''){
		if(!$merchid || !$code){
			return false;
		}
		$merch=pdo_get('jy_merch_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchid));
		$onewechat=$merch['onewechat']?json_decode($merch['onewechat'],true):array();
		if(!$_SESSION['openid'.$merchid] && !$_SESSION['isopenid'.$merchid]){
			//如果有code，根据code获取粉丝openid
			$url='https://api.weixin.qq.com/sns/jscode2session?appid='.$onewechat['minappid'].'&secret='.$onewechat['minappsecret'].'&js_code='.$code.'&grant_type=authorization_code';
			$result=cfc('http')->ihttp_get($url);
			$result=json_decode($result['content'],true);
			$_SESSION['openid'.$merchid]=$result['openid'];
		}
		return false;
	}
	public function wechat_auth_base_url($merchid=0){
		if($_SESSION['isopenid'.$merchid]>=2){
			return false;
		}
		$_SESSION['isopenid'.$merchid] = intval($_SESSION['isopenid'.$merchid]);
		$_SESSION['isopenid'.$merchid] += 1;
		$backurl=urlencode(download_url('jy_merch/member.auth/base/merchid='.$merchid));
		$onewechat = pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'onewechat');
		$onewechat=json_decode($onewechat,true);
		if(!$onewechat || !$onewechat['isopen'] || !$onewechat['appid'] || !$onewechat['appsecret']){
			return false;
		}
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$onewechat['appid'].'&redirect_uri='.$backurl.'&response_type=code&scope=snsapi_base&state=getcode#wechat_redirect';
		return $url;
	}
	/*
		成为商户会员;
		每个商户有自己的会员体系（具体如何成为商户的会员，请移步基本设置--商户会员体系）；
	*/
	public function up_addmember($merchid=0,$uid=0){
			$uid=$uid?:$_SESSION['uid'];
			$merch_2vip=$this->setting['merch_2vip'];
			if($merch_2vip==0){
				$isbuy=pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'ispay'=>1));
				if($isbuy['id']){
					$this->addmember($merchid,$uid);
				}
			}elseif($merch_2vip==1){
				$isbuy=pdo_get('jy_merch_creditlog',array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'is_add'=>1,'type'=>2));
				if($isbuy['id']){
					$this->addmember($merchid,$uid);
				}
			}elseif($merch_2vip==2){
				$this->addmember($merchid,$uid);
			}else{
				$this->addmember($merchid,$uid);
			}
			return false;
	}
	public function addmember($merchid=0,$uid=0,$islogin=false){
	        global $_AR;
			$uid=$uid?:$_SESSION['uid'];
			$check=pdo_get('jy_merch_member',array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			if($check['id']){
				return false;
			}
			$fmerchid=pdo_getcolumn('jy_merch_member',array('mid'=>$uid,'uniacid'=>$_SESSION['uniacid']),'fmerchid');
			$agent_id=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),'fromuser');
			$data=array(
                    'uniacid'=>$_SESSION['uniacid'],
                    'merchid'=>$merchid,
					'fmerchid'=>$fmerchid?:$merchid,
                    'mid'=>$uid,
                    'fromuser'=>$agent_id?:$_SESSION['fromuser'],
                    'createtime'=>time(),
            );
			pdo_insert('jy_merch_member',$data);
			$this->publish('member.add',$data);
            if($islogin){
                $_SESSION['forward_url']=$_AR['access_json'];
                exi('','error','jy_merch/member.login/');
            }
            return true;
	}
	public function detail($merchid,$uid=0){
			$member=$this->getdetail($merchid,$uid);
			return $member;
	}
	public function getdetail($merchid,$uid=0){
			$uid=$uid?:$_SESSION['uid'];
			$member=pdo_get('jy_merch_member',array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			if(!$member['id']){
				$this->addmember($merchid,$uid);
			}
			$member2=pdo_get('core_members',array('id'=>$_SESSION['uid']),array('username','avatar','nickname'));
			$member=array_merge($member2,$member);
			return $member;
	}
	public function get_merch_type($merchid=0,$uid=0){
			$uid=$uid?:$_SESSION['uid'];
			if(!$merchid){
				return false;
			}
			$cateid=pdo_getcolumn('jy_merch_user',array('id'=>$merchid,'uniacid'=>$_SESSION['uniacid']),'cateid');	
			$type=pdo_getcolumn('jy_merch_category',array('id'=>$cateid,'uniacid'=>$_SESSION['uniacid']),'type');	
			return $type;
	}
	public function getred($uid=0){
			$uid=$uid?:$_SESSION['uid'];
			$sale_reds=$this->pdo_getall('feelog',array('type'=>0,'status'=>0,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			foreach($sale_reds as $sv){
				if($sv['fee']>0){
					pdo_update('jy_weishop_member',array('redfee +='=>$sv['fee']),array('mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
				}
			}
			$this->pdo_update('feelog',array('status'=>1),array('type'=>0,'status'=>0,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			return true;
	}
	public function tixianred($uid=0){
			$uid=$uid?:$_SESSION['uid'];
			$this->getred($uid);
			$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$istixian=pdo_get('jy_merch_feelog',array('createtime >='=>$daytime,'type'=>1,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			if($istixian['id']){
				exi('您今天已经领红包了，明天再来吧！','error');
			}
			$member=pdo_get('jy_weishop_member',array('mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			$level=pdo_get('jy_weishop_member_level',array('id'=>$member['level'],'uniacid'=>$_SESSION['uniacid']));
			if(!$level['can_tred']){
				exi('当前等级不支持提现！','error');
			}
			if($member['redfee']<=1){
				exi('当前账户积分红包不足1元，不可领取红包！','error');
			}
			if($this->setting['ti_max']<1){
				exi('未设置领取红包的最大额度参数！','error');
			}
			$ti_max=$member['redfee']>$this->setting['ti_max']?$this->setting['ti_max']:$member['redfee'];
			$fee=rand(1,$ti_max);
			//提现到微信零钱
			$params=array(
				'money'=>$fee,
				'merchid'=>$member['merchid'],
				'remark'=>'红包提现',
			);
			$this->pay_out($uid,$params);
			$feelog=array(
				'mid'=>$uid,
				'msg'=>'领取红包到零钱',
				'fee'=>$fee,
				'status'=>0,
			);
			$this->model('model')->set_feelog($feelog,1);
			pdo_update('jy_weishop_member',array('redfee -='=>$fee),array('mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			return true;
	}
	/*
		获取credit
	*/
	public function creditdata($member){
		$credit_types=credit_types();
		$creditdata=array();
		$onecredit=pdo_getcolumn('jy_merch_user',array('id'=>$member['merchid'],'uniacid'=>$_SESSION['uniacid']),'onecredit');
		$onecredit=$onecredit?json_decode($onecredit,true):'';
		$payset=$onecredit?:uni_setting('pay');
		foreach($credit_types as $k=>$title){
			if($k>2 && $payset['credit'.$k]!=1){
				continue;
			}
			$creditkey='credit'.$k;
			$rate=$payset['credit'.$k.'_rate']?:1;
			$dirate=$payset['credit'.$k.'_dirate']?:100;
			$creditdata[]=array(
				'rate'=>$rate,
				'dirate'=>$dirate,
				'type'=>$k,
				'field'=>$creditkey,
				'title'=>$title,
				'value'=>$member[$creditkey]
			);
		}
		return $creditdata;
	}
	public function addcreditlog($merchid=0,$uid=0,$fee=0,$type=2,$isadd=1,$remark=''){
			if($_SESSION['this']=='manage' && !$_SESSION['isfounder'] && $_SESSION['user']['type'] && $_SESSION['user']['type']!=3){
				cfc('user')->checksql_perms(3);
			}
			$uid=$uid?:$_SESSION['uid'];
			if(!$fee || !$merchid){
				return false;
			}
			if($isadd && $type==2){
				$this->addmember($merchid,$uid);
				pdo_update('jy_merch_member',array('credit2 +='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if(!$isadd && $type==2){
				pdo_update('jy_merch_member',array('credit2 -='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if($isadd && $type==3){
				$this->addmember($merchid,$uid);
				pdo_update('jy_merch_member',array('credit3 +='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if(!$isadd && $type==3){
				pdo_update('jy_merch_member',array('credit3 -='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if($isadd && $type==4){
				$this->addmember($merchid,$uid);
				pdo_update('jy_merch_member',array('credit4 +='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if(!$isadd && $type==4){
				pdo_update('jy_merch_member',array('credit4 -='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if($isadd && $type==5){
				$this->addmember($merchid,$uid);
				pdo_update('jy_merch_member',array('credit5 +='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			if(!$isadd && $type==5){
				pdo_update('jy_merch_member',array('credit5 -='=>$fee),array('merchid'=>$merchid,'mid'=>$uid,'uniacid'=>$_SESSION['uniacid']));
			}
			$data=array(
				'uniacid'=>$_SESSION['uniacid'],
				'merchid'=>$merchid,
				'mid'=>$uid,
				'type'=>$type,
				'is_add'=>$isadd,
				'fee'=>$fee,
				'remark'=>$remark,
				'createtime'=>time(),
			);
			pdo_insert('jy_merch_creditlog',$data);
			return true;
	}
	/*
		积分余额变更,$tag用于区分来源
	*/
	public function member_credit($merchid,$mid,$field,$value,$is_add='',$from_plugin='',$remark='',$tag='',$op_mid=0,$more=array()){
		if($_SESSION['this']=='manage' && !$_SESSION['isfounder'] && $_SESSION['user']['type'] && $_SESSION['user']['type']!=3){
			cfc('user')->checksql_perms(3);
		}
		$fields=array('credit1','credit2','credit3','credit4','credit5','credit6','credit1_fz','credit2_fz','credit3_fz','credit4_fz','credit5_fz','credit6_fz');
		if(!in_array($field,$fields)){
			return error('要修改的字段不被允许修改');
		}
		if(!$remark){
			exi('请设置变更积分余额的备注！','error');
		}
		if($is_add){
			$isone_dongjie=$this->setting['isone_dongjie'];
			if($isone_dongjie && $more['ismerchpay']){
				$field=$field.'_fz';
			}
			$data=array($field.' +='=>$value);
		}else{
			$fieldfee=pdo_getcolumn('jy_merch_member',array('merchid'=>$merchid,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),$field);
			if($fieldfee<$value){
				return false;
			}else{
				$data=array($field.' -='=>$value);
			}
		}
		pdo_update('jy_merch_member',$data,array('merchid'=>$merchid,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		$type=substr($field, -1);
		$type=intval($type);
		if($type){
			$log=array(
				'uniacid'=>$_SESSION['uniacid'],
				'merchid'=>$merchid,
				'mid'=>$mid,
				'type'=>$type,
				'is_add'=>$is_add?1:0,
				'fee'=>$value,
				'remark'=>$remark,
				'plugin'=>$from_plugin,
				'tag'=>$tag,
				'op_mid'=>$op_mid,
				'ordersn'=>$more['ordersn'],
				'createtime'=>TIMESTAMP
			);
			pdo_insert('jy_merch_creditlog',$log);
			$log_id=pdo_insertid();
		}
		return $log_id?:$field;
	}
	public function get_level(){
		$merch_user=pdo_get('jy_merch_user',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']),array('groupid'),'groupid desc');
		$memberlevel_id=pdo_getcolumn('jy_merch_group',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merch_user['groupid']),'memberlevel_id');
		return $memberlevel_id;
	}
	//增加积分
	public function add_credit1($merchid,$mid,$money,$remark='',$from_plugin='',$tag=''){
		return $this->member_credit($merchid,$mid,'credit1',$money,true,$from_plugin,$remark,$tag);
	}
	//增加余额
	public function add_credit2($merchid,$mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($merchid,$mid,'credit2',$money,true,$from_plugin,$remark);
	}
	//减少积分
	public function cut_credit1($merchid,$mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($merchid,$mid,'credit1',$money,false,$from_plugin,$remark);
	}
	//减少余额
	public function cut_credit2($merchid,$mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($merchid,$mid,'credit2',$money,false,$from_plugin,$remark);
	}
	//冻结
	public function fz_credit($merchid,$mid,$money,$remark='',$from_plugin='',$type=1){
		return $this->member_credit($merchid,$mid,'credit'.$type.'_fz',$money,true,$from_plugin,$remark);
	}
	//提现申请冻结
	public function fz_credit2($merchid,$mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($merchid,$mid,'credit2_fz',$money,true,$from_plugin,$remark);
	}
	//提现申请解冻
	public function thaw_credit2($merchid,$mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($merchid,$mid,'credit2_fz',$money,false,$from_plugin,$remark);
	}
	//提现申请解冻
	public function thaw_credit($merchid,$mid,$money,$remark='',$from_plugin='',$type=1){
		return $this->member_credit($merchid,$mid,'credit'.$type.'_fz',$money,false,$from_plugin,$remark);
	}
    public function member_show($mid,$merchid=0,$default_url='',$default=array()){
        $coremember=pdo_get('core_members',array('id'=>intval($mid)),array('id','nickname','realname','username','mobile','avatar','from_os'));
        $merchmember=pdo_get('jy_merch_member',array('mid'=>intval($mid),'merchid'=>$merchid),array('name','mobile'));
		if(!$coremember && !$merchmember){
            $member=$default?:array('nickname'=>'无');
        }else{
            $member['url']=$default_url?str_replace('{mid}',$coremember['id'],$default_url):'';
            $member['nickname']=$merchmember['name']?:$coremember['nickname'];
            $member['nickname']=$member['nickname']?:$coremember['username'];
            $member['avatar']=tomedia($coremember['avatar']);
            $member['mobile']=$merchmember['mobile']?:$coremember['mobile'];
        }
		$member=array_merge($coremember,$member);
        return $member;
    }
	function pay($cash_id){
		$cash=pdo_get('core_member_cash',array('id'=>$cash_id));
		if(!$cash){
			exi('提现打款失败，提现订单不存在！','error');
		}
		if($cash['status']){
			exi('提现打款失败，该提现订单已打款！','error');
		}
		if(!$cash){
			exi('提现打款失败，提现订单不存在！','error');
		}
		//$this->check_cash_fee($cash['mid'],$cash['money']);
		$params=array(
			'money'=>$cash['cash_money'],
			'remark'=>'会员余额提现',
			'merchid'=>$cash['merchid'],
		);
		if($cash['merchid']){
			$pay_out_id=model('jy_merch/member')->pay_out($cash['mid'],$params);
		}else{
			exi('提现打款失败，不属于商户订单！','error');
		}
		$update=array(
			'status'=>1,
			'pay_out_id'=>$pay_out_id,
		);
		pdo_update('core_member_cash',$update,array('id'=>$cash['id']));
		$credit_type=$cash['credit_type']?:2;
		if($credit_type==2){
			$money=$cash['money'];
		}else{
			$money=$cash['credit_fee'];
		}
		$this->thaw_credit($cash['merchid'],$cash['mid'],$money,'会员提现成功','core',$credit_type);
		return true;
	}
	public function pay_out($mid,$params){
		if(!$mid || !$params){
			exi('付款失败！参数错误！','error');
		}
		if(!$params['money'] || $params['money']<=0){
			exi('付款失败！付款金额必须大于0');
		}
		if(!$params['remark']){
			exi('付款失败！必须设置付款备注！','error');
		}
		$money=intval($params['money']*100)/100;
		$pay_out=array(
			'uniacid'=>$_SESSION['uniacid'],
			'merchid'=>$params['merchid'],
			'trade_no'=>get_ordersn('core_payout_log','trade_no','OUT'),
			'mid'=>$mid,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'remark'=>$params['remark'],
			'status'=>0,
		);
		pdo_insert('core_payout_log',$pay_out);
		$pay_id=pdo_insertid();
		$onewechat=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$params['merchid']),'onewechat');
        $onewechat=json_decode($onewechat,true);
        if($onewechat && $onewechat['isopen'] && $onewechat['appid'] && $onewechat['wechat_mchid']){
               $config=array(
                            'appid'=>$onewechat['appid'],
                            'mch_id'=>$onewechat['wechat_mchid'],
                            'key'=>$onewechat['wechat_miyue'],
                            'apiclient_cert'=>$onewechat['cert_file']?ROOT_AT.$onewechat['cert_file']:'',
                            'apiclient_key'=>$onewechat['key_file']?ROOT_AT.$onewechat['key_file']:'',
               );
        }else{
			exi("打款失败！具体原因为：该商户不支持微信打款！",'error');
		}
		$data=array(
			'mch_billno'=>$pay_out['trade_no'],
			'openid'=>$pay_out['mid'],
			'money'=>$pay_out['money'],
			'remark'=>$pay_out['remark'],
		);
		$res=model('core/wechat_pay',$config)->mch_pay($data);
		if($res['return_code']!='SUCCESS' || $res['result_code']!='SUCCESS'){
			//exi("打款失败！具体原因为：{$return['return_msg']}|{$return['err_code']}|{$return['err_code_des']}",'error');
		}
		$update=array(
			'status'=>1,
			'pay_type'=>'wechat',
			'out_trade_no'=>$res['payment_no'],
		);
		pdo_update('core_payout_log',$update,array('id'=>$pay_id));
		return $pay_id;
	}
}